package com.ruoyi.web.controller.sz;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.mysql.cj.util.DataTypeUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.system.domain.sz.SzPersonal;
import com.ruoyi.system.domain.sz.SzPersonalRecord;
import com.ruoyi.system.domain.sz.SzPersonalVO;
import com.ruoyi.system.service.sz.ISzPersonalService;
import com.ruoyi.system.task.SzPersonalTask;
import com.ruoyi.util.WordUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;

import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import static com.ruoyi.common.constant.TimeLineConstants.SYS_USER_SEX;
import static com.ruoyi.common.constant.TimeLineConstants.SZ_STAFF_NATION;

/**
 * 个人信息Controller
 * 
 * @author ruoyi
 * @date 2024-03-14
 */
@Anonymous
@RestController
@RequestMapping("/sz/personal")
public class SzPersonalController extends BaseController
{
    @Autowired
    private ISzPersonalService szPersonalService;
    @Value("${word.source}")
    private String sourceName;

    @Value("${word.personal}")
    private String personalTemple;


    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    SzPersonalTask szPersonalTask;

    /**
     * 查询个人信息列表
     */
//    @PreAuthorize("@ss.hasPermi('sz:personal:list')")
    @GetMapping("/list")
    public TableDataInfo list(SzPersonal szPersonal)
    {
        startPage();
        List<SzPersonal> list = szPersonalService.selectSzPersonalList(szPersonal);
        return getDataTable(list);
    }

    /**
     * 导出个人信息列表
     */
//    @PreAuthorize("@ss.hasPermi('sz:personal:export')")
//    @Log(title = "个人信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SzPersonal szPersonal)
    {
        List<SzPersonal> list = szPersonalService.selectSzPersonalList(szPersonal);
        if("0".equals(szPersonal.getStatus())){
            ExcelUtil<SzPersonal> util = new ExcelUtil<SzPersonal>(SzPersonal.class);
            util.exportExcel(response, list, "个人信息数据");
        }else{
            List<SzPersonalVO> collect = list.stream().map(p -> {
                SzPersonalVO vo = new SzPersonalVO();
                vo.setPersonalName(p.getPersonalName());
                SzPersonalRecord szPersonalRecord = p.getSzPersonalRecord();
                if(null != szPersonalRecord) {
                    vo.setJobTitle(p.getSzPersonalRecord().getJobTitle());
                    vo.setCurrentPosition(p.getSzPersonalRecord().getCurrentPosition());
                    vo.setUnit(p.getSzPersonalRecord().getUnit());
                }
                vo.setPhone(p.getPhone());
                vo.setSensitiveWorkYears(p.getSensitiveWorkYears());
                return vo;
            }).collect(Collectors.toList());
            ExcelUtil<SzPersonalVO> util = new ExcelUtil<SzPersonalVO>(SzPersonalVO.class);
            util.exportExcel(response, collect, "个人信息数据");
        }

    }

    /**
     * 导出个人信息列表
     */
//    @PreAuthorize("@ss.hasPermi('sz:personal:export')")
//    @Log(title = "个人信息", businessType = BusinessType.EXPORT)
    @GetMapping("/generate/{personalId}")
    public void generate(HttpServletResponse response, @PathVariable("personalId") Long personalId) throws IOException {
        SzPersonal szPersonal1 = szPersonalService.selectSzPersonalByPersonalId(personalId);

        Map<String, Object> data = new HashMap<>();
        //姓名
        data.put("personalName", szPersonal1.getPersonalName());
        String sex = szPersonal1.getSex();
        if(StringUtils.isNotBlank(sex)) {
            //性别
            data.put("sex", DictUtils.getDictLabel(SYS_USER_SEX, sex));
        }
        //民族
        String nation = szPersonal1.getNation();
        if(StringUtils.isNotBlank(nation)) {
            data.put("nation", DictUtils.getDictLabel(SZ_STAFF_NATION, nation));
        }
        Date birthday = szPersonal1.getBirthday();
        if(null != birthday) {
            //生日日期
            data.put("birthdate", DateUtils.parseDateToStr("yyyy-MM-dd", birthday));
        }
        //籍贯
        data.put("nativePlace", szPersonal1.getNativePlace());
        //家庭地址
        data.put("familyAddress", szPersonal1.getFamilyAddress());

        FileInputStream fileInputStream = null;
        OutputStream outputStream = null;
        try {
            String fileName = "filled_personal_info.docx";
            String sourceAdr = RuoYiConfig.getWordPath();
            String  source = WordUtils.createDoc(data, freeMarkerConfigurer, personalTemple,fileName,sourceAdr);
            File file = new File(source);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentLength((int) file.length());

            fileInputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();

            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(null != fileInputStream){
                fileInputStream.close();
            }
            if(null != outputStream){
                outputStream.close();
            }
        }


    }

    /**
     * 获取个人信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('sz:personal:query')")
    @GetMapping(value = "/{personalId}")
    public AjaxResult getInfo(@PathVariable("personalId") Long personalId)
    {
        return success(szPersonalService.selectSzPersonalByPersonalId(personalId));
    }

    /**
     * 新增个人信息
     */
//    @PreAuthorize("@ss.hasPermi('sz:personal:add')")
//    @Log(title = "个人信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SzPersonal szPersonal)
    {
        szPersonalService.insertSzPersonal(szPersonal);
        return success(szPersonal);
    }

    @GetMapping("/Political")
    public AjaxResult rySzPoliticalReview(){
        szPersonalTask.rySzPoliticalReview();
        return success();
    }

    /**
     * 修改个人信息
     */
//    @PreAuthorize("@ss.hasPermi('sz:personal:edit')")
//    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SzPersonal szPersonal)
    {
        return toAjax(szPersonalService.updateSzPersonal(szPersonal));
    }

    /**
     * 删除个人信息
     */
//    @PreAuthorize("@ss.hasPermi('sz:personal:remove')")
//    @Log(title = "个人信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{personalIds}")
    public AjaxResult remove(@PathVariable Long[] personalIds)
    {
        return toAjax(szPersonalService.deleteSzPersonalByPersonalIds(personalIds));
    }



    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file,@RequestParam("personalId") Long personalId) throws Exception
    {
        if (!file.isEmpty())
        {
            if(null != personalId){
                SzPersonal szPersonal =  new SzPersonal();
                String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
                szPersonal.setAvatar(avatar);
                szPersonal.setPersonalId(personalId);
                if(szPersonalService.updatePersonalAvatar(szPersonal)) {
                    AjaxResult ajax = AjaxResult.success();
                    ajax.put("imgUrl", avatar);
                    return ajax;
                }
            }

        }
        return error("上传图片异常，请联系管理员");
    }

//    @PreAuthorize("@ss.hasPermi('sz:personal:edit')")
//    @Log(title = "个人信息-岗前备案", businessType = BusinessType.UPDATE)
    @PutMapping("/updateRecord")
    public AjaxResult updateRecord(@RequestBody SzPersonal szPersonal)
    {
        return toAjax(szPersonalService.updateSzPersonalRecord(szPersonal));
    }


}
